package cn.lkp.mall.ware.listener;

import cn.lkp.common.to.mq.StockLockedTo;
import cn.lkp.mall.ware.service.WareSkuService;
import cn.lkp.mall.ware.to.OrderTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;
    /**
     * 库存自动解锁：
     *     下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存自动解锁
     *     只要解锁库存的信息失败，一定要告诉服务解锁库存失败
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message,
                                         Channel channel) throws IOException {
        System.out.println("收到库存解锁信息：");
        try{
            wareSkuService.unLockStock(to);
            //手动ack删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch(Exception e){
            //消息拒绝以后重新放在队列里面，让别人继续消费解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 收到订单关闭，解锁库存
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message,
                                        Channel channel) throws IOException{
        System.out.println("收到订单关闭，准备解锁库存的信息...");
        try{
            wareSkuService.unLockStock(to);
            //手动ack删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch(Exception e){
            //消息拒绝以后重新放在队列里面，让别人继续消费解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
